import base64
import pickle

from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from random import randint

from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializers import SKUSerializers
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from user.models import User
from user.serializer import UserSerializer, UserDetailSerializer, UserEmailSerializer, VerifyEmailSerializer, \
    AddUserBrowsingHistorySerializers
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.

# get  sms_code/mobile  ok

class SMSCodeView(APIView):
    def get(self, request, mobile):
        # 判断60s
        # 建立链接
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s' % mobile)

        if flag:
            return Response({'message': 'error'}, status=401)
        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print('短信验证码: %s' % sms_code)
        # 保存到redis缓存
        pl = conn.pipeline()  # 生成管道对象
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('sms_flag_%s' % mobile, 60, 1)
        pl.execute()  # 管道调用

        # 发送短信
        # Celery调用，异步执行
        send_sms_code.delay(mobile, sms_code)
        # 返回结果
        return Response({'message': 'ok'})


class UserNameView(APIView):
    def get(self, request, username):
        # 查询用户数量
        count = User.objects.filter(username=username).count()

        # 返回查询的数量
        return Response({
            'username': username,
            'count': count
        })


class MobileView(APIView):
    def get(self, request, mobile):
        # 查询手机号数据
        count = User.objects.filter(mobile=mobile).count()

        # 返回查询的数量
        return Response({
            'mobile': mobile,
            'count': count
        })


class UserView(CreateAPIView):
    serializer_class = UserSerializer


class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]  # 权限用户，（认证用户）

    # 　重写get_object方法返回指定数据对象
    def get_object(self):
        print(self.request.user)

        return self.request.user


class UserEmailView(UpdateAPIView):
    serializer_class = UserEmailSerializer

    # 重写get_object方法返回制定数据对象
    def get_object(self):
        print(self.request.user)
        return self.request.user


class VerifyEmailView(GenericAPIView):
    serializer_class = VerifyEmailSerializer

    def get(self, request):
        # 获取用户数据
        data = request.query_params

        # 数据验证
        ser = self.get_serializer(data=data)
        ser.is_valid()
        print(ser.errors)

        # 　更新用户邮箱状态
        data = ser.validated_data['data']
        id = data['id']
        username = data['username']

        try:
            user = User.objects.get(id=id, username=username)
        except:
            return Response({'errors:用户不存在'}, status=400)

        user.email_active = True
        user.save()

        # 　结果返回
        return Response({'email_actibe': True})


class AddUserBrowsingHistoryView(CreateAPIView):
    # 用户浏览记录

    permission_classes = [IsAuthenticated]  # 用户权限验证
    serializer_class = AddUserBrowsingHistorySerializers

    def get(self, request):
        user = request.user

        # 建立连接
        conn = get_redis_connection('history')

        sku_id_list = conn.lrange('history_%s' % user.id, 0, 5)

        # 查询数据
        sku_list = []
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id=sku_id)
            print('用户浏览记录为:%s'%sku.name)
            sku_list.append(sku)

        # 序列化返回
        ser = SKUSerializers(sku_list, many=True)


        return Response(ser.data)


class UserAuthorizeView(ObtainJSONWebToken):
    # 重写登陆业务逻辑
    def post(self, request, *args, **kwargs):

        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)
        # 获取用户对象
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            response=merge_cart_cookie_to_redis(request, response, user)

        return response
